package com.shop.myweb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shop.myweb.common.R;
import com.shop.myweb.entity.Goods;
import com.shop.myweb.entity.ShoppingCart;
import com.shop.myweb.service.GoodsService;
import com.shop.myweb.service.ShoppingCartService;
import com.shop.myweb.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: ZhuangShuo
 * @date: 2023/4/25 19:33
 * @description:
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private GoodsService goodsService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查看购物车
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(Long id) {
        log.info("查看购物车...");

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, id);

        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        return R.success(list);
    }


    /**
     * 添加商品到购物车
     *
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        log.info("添加商品到购物车...");
        //查询当前商品是否在购物车中
        Long goodsId = shoppingCart.getGoodsId();

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, shoppingCart.getUserId());

        if (goodsId != null) {
            //在用户id下查找商品id
            queryWrapper.eq(ShoppingCart::getGoodsId, shoppingCart.getGoodsId());


            //SQL: select * from shopping_cart where user_id = ? and goods_id = ?
            ShoppingCart cartServiceOne = shoppingCartService.getOne(queryWrapper);

            //查询当前商品是否在购物车中
            if (cartServiceOne != null) {
                //如果已经存在，就在原来数量基础上加
                Integer number = cartServiceOne.getAmount();
                cartServiceOne.setAmount(cartServiceOne.getAmount() + shoppingCart.getAmount());
                cartServiceOne.setCreateTime(LocalDateTime.now());
                shoppingCartService.updateById(cartServiceOne);
            } else {
                //如果不存在，则添加到购物车
                shoppingCart.setAmount(shoppingCart.getAmount());
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCartService.save(shoppingCart);
                cartServiceOne = shoppingCart;
            }

            if (RedisUtils.isRedisAvailable(redisTemplate)) {
                String key = "goods_" + goodsId;
                Goods goods = (Goods) redisTemplate.opsForValue().get(key);
                if (goods != null) {
                    redisTemplate.delete(key);
                }
            }

            return R.success(cartServiceOne);
        } else return R.error("添加失败");
    }

    /**
     * 更新商品信息
     */
    @PutMapping("/update")
    @Transactional
    public R<ShoppingCart> update(@RequestBody ShoppingCart shoppingCart) {
        Long id = shoppingCart.getGoodsId();
        Long shoppingCartId = shoppingCart.getId();
        int amount = shoppingCart.getAmount();

        LambdaQueryWrapper<Goods> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Goods::getId, id);
        Goods goods1 = goodsService.getOne(queryWrapper1);

        int goods_amount = goods1.getAmount();

        if (amount > goods_amount) {
            return R.error("商品库存不足！");
        }

        LambdaQueryWrapper<ShoppingCart> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(ShoppingCart::getId, shoppingCartId);
        shoppingCart.setCreateTime(LocalDateTime.now());

        shoppingCartService.update(shoppingCart, queryWrapper2);

        return R.success(shoppingCart);
    }

    /**
     * 删除指定商品
     *
     * @return
     */
    @DeleteMapping("/delete")
    public R<String> delete(Long id) {

        shoppingCartService.removeById(id);

        return R.success("删除成功");
    }


    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(Long id) {
        log.info("清空购物车...");

        //SQL: delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, id);

        shoppingCartService.remove(queryWrapper);

        return R.success("清空购物车成功");
    }

    @DeleteMapping
    public R<String> deleteOne(Long id) {


        shoppingCartService.removeById(id);

        return R.success("删除成功!");

    }

    @PutMapping("/changeAmount")
    public R<String> changeAmount(@RequestBody ShoppingCart shoppingCart) {

        Long goodsId = shoppingCart.getGoodsId();
        int amount = shoppingCart.getAmount();

        Goods goods = goodsService.getById(goodsId);
        int inventory = goods.getAmount();

        if (inventory >= amount) {
            inventory -= amount;
            goods.setAmount(inventory);
            if (RedisUtils.isRedisAvailable(redisTemplate)) {
                String key = "goods_" + goods.getId();
                redisTemplate.delete(key);
            }
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.updateById(shoppingCart);
            return R.success("修改数量成功！");
        } else {
            return R.error("商品库存不足，请选择小于" + inventory + "件！");
        }
    }
}
